/***
 * @Date: 2020-07-13 18:10:55
 * @LastEditors: leehave
 * @LastEditTime: 2020-07-14 09:44:04
 */
/***
 * @Date: 2020-07-13 18:10:55
 * @LastEditors: leehave
 * @LastEditTime: 2020-07-14 09:14:44
 */

import router from "@/router";
import store from "@/store";
import { Notify } from "vant";
import defaultSetting from "../setting";
const { topProgress } = defaultSetting;
import NProgress from "nprogress"; // progress bar
import "@/assets/less/nprogress.less";
import { setDocumentTitle } from "@/utils/dom-util";
import { getToken } from "@/utils/storage";
import staticPath from "@/assets/json/index";
import wechatAuth from "@/plugins/wechatAuth";
import { isIOS } from '@/utils/index';
import { initWxJSDK } from '@/utils/wx-util'
import qs from 'qs';

wechatAuth.setAppId(process.env.VUE_APP_WECHAT_APPID)
if (topProgress) {
  NProgress.configure({ showSpinner: false }); // NProgress Configuration
}

const whiteList = ["login", "register", "home", "404"]; // 路由白名单
// const mainPath = ['home','user','']
const defaultPath = "/";

router.beforeEach(async (to, from, next) => {
  // console.log(to,from, next, 'to from, next')
  if (topProgress) NProgress.start(); // start progress bar

  // 在白名单，直接进入
  if (whiteList.indexOf(to.path) !== -1) {
    return next();
  }
  

  // 设置页面标题
  setDocumentTitle(to.meta);

  const {loginStatus,userInfo} = store.getters
  console.log(loginStatus,'loginStatus')
  next()
  switch (Number(loginStatus)) {
    case 0:
      // 获取跳转地址
      wechatAuth.redirect_uri = processUrl()
      await store.dispatch('user/setLoginStatus', 1)
      window.location.href = wechatAuth.authUrl
      console.log(wechatAuth.authUrl,'wechatAuth.authUrl')
      console.log('userInfo router beforeeach statusCode 0',userInfo)
      break
    case 1:
      
      try {
        wechatAuth.returnFromWechat(window.location.href)
        const code = wechatAuth.code
        console.log(code,'code')
        // 通过code换取token
        if(code == 0 || code == undefined){
          // await store.dispatch('user/fedLogOut') // 刷新重新来一遍
          await store.dispatch('user/setLoginStatus', 0) 
          return
        }else{
          await store.dispatch('user/setLoginStatus', 2)
          await store.dispatch('user/loginWechatAuth', code)

          console.log('userInfo router beforeeach statusCode 1',userInfo)
        }
        
        // hash
        if (process.env.NODE_ENV !== 'development' && router.mode === 'hash') {
          window.location.href = window.location.origin + window.location.pathname + window.location.hash

          
        } else {
          next()
        }
      } catch (err) {
        await store.dispatch('user/setLoginStatus', 0)
        next('/404')
      }
      break
    case 2:
      console.log('userInfo router beforeeach statusCode 2')
      next()
      break
    default:
      break
  }
  
});

function processUrl() {
  // 本地环境换通过auth.html拿code
  if (process.env.NODE_ENV === 'development') {
    // 中间授权页地址
     return `${process.env.VUE_APP_WECHAT_AUTH_URL}?backUrl=${window.location.href}`
  }
  const url = window.location.href
  // 解决多次登录url添加重复的code与state问题
  const urlParams = qs.parse(url.split('?')[1])
  let redirectUrl = url
  if (urlParams.code && urlParams.state) {
    delete urlParams.code
    delete urlParams.state
    const query = qs.stringify(urlParams)
    if (query.length) {
      redirectUrl = `${url.split('?')[0]}?${query}`
    } else {
      redirectUrl = `${url.split('?')[0]}`
    }
  }
  return redirectUrl
}


function findMenuParent(tag) {
  let tagCurrent = [];
  const menu = store.getters.menu;
  tagCurrent.push(tag);
  return tagCurrent;
}
const navigation = ["/home","/huli", "/user"];
router.afterEach( async () => {
  setTimeout(() => {
    navigation.map((item, index) => {
      if (router.currentRoute.path.includes(item)) {
        store.commit("app/regexTabActive", staticPath.tab[index]);
      } else {
        // store.commit("app/regexTabActive", staticPath.tab[1]);
      }
    });
  }, 0);
  const {loginStatus,userInfo} = store.getters
  if(Object.keys(userInfo).length === 0){
    // await store.dispatch('user/setLoginStatus', 0)
    // await store.dispatch('user/fedLogOut')
  }
  let signLink;
  if( isIOS() ){
    // 记录进入app时的url
    if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
      window.entryUrl = location.href.split('#')[0]
    }
    // 将http://028h5.cn/?i=xxxxxxxxxx 转为http://028h5.cn/index?i=xxxxxxxxxx 
    if( window.entryUrl.indexOf('/?') != -1 ){
      window.entryUrl = window.entryUrl.split('/?')[0]+'/index?'+window.entryUrl.split('/?')[1]
    }
    // 进行签名的时候  Android 不用使用之前的链接， ios 需要
    signLink =  /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;
    
  }
  else{
    signLink = window.location.href.split('#')[0]
  }
  if(signLink == undefined || signLink == ''){
    return
  }

  initWxJSDK(['scanQRCode','chooseImage', 'uploadImage', 'previewImage','chooseWXPay'],['wx-open-launch-weapp'],signLink)

  let routerPath = router.currentRoute;
  
  if (topProgress) NProgress.done(); // finish progress bar
});

